package com.itheima.youdianda.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.youdianda.domain.YddTag;
import com.itheima.youdianda.common.Result;
import com.itheima.youdianda.service.YddTagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * @author pk
 * @date 2022/09/06/21:23
 */
@RestController
@RequestMapping("/ydd_tag")
public class TagController {

    @Autowired
    private YddTagService tagService;

    /**
     * 标签修改
     * @param tag
     * @return
     */
    @PostMapping("/update")
    @CacheEvict(value = "tagCache",allEntries = true)
    public Result update(@RequestBody YddTag tag){

        tagService.updateById(tag);
        return Result.ok("修改成功");
    }

    /**
     * 标签添加
     * @param tag
     * @return
     */
    @PostMapping("/add")
    @CacheEvict(value = "tagCache",allEntries = true)
    public Result add(@RequestBody YddTag tag){

        tagService.save(tag);
        return Result.ok("标签添加成功");

    }

    /**
     * 标签列表-全部
     * @return
     */
    @GetMapping("/all")
    @Cacheable(value = "tagCache",keyGenerator = "commonKeyGenerator")
    public Result all(){
        //返回标签集合
        return Result.ok(tagService.list());
    }

    /**
     * 标签详情
     * 修改标签时的回显
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    @Cacheable(value = "tagCache",key = "#id")
    public Result rowInfo(Integer id){

        YddTag tag = tagService.getById(id);
        return Result.ok(tag);

    }

    /**
     * 标签列表-分页
     * @param page
     * @param limit
     * @param tagname
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "tagCache",keyGenerator = "commonKeyGenerator")
    public Result list(Integer page,Integer limit,String tagname){
        Page pageInfo = new Page(page, limit);

        LambdaQueryWrapper<YddTag> lqw = new LambdaQueryWrapper<>();
        lqw.like(tagname!=null,YddTag::getTagname,tagname);
        lqw.orderByAsc(YddTag::getId);

        tagService.page(pageInfo,lqw);

        List<YddTag> records = pageInfo.getRecords();
        //创建map集合容器
        HashMap<String, Object> map = new HashMap<>();
        map.put("count",pageInfo.getTotal());
        map.put("totalPages",pageInfo.getPages());
        map.put("pageSize",limit);
        map.put("currentPage",page);
        map.put("data",records);
        return Result.ok(map);

    }

    /**
     * 标签删除
     * @return
     */
    @GetMapping("/del")
    @CacheEvict(value = "tagCache",allEntries = true)
    public Result del(Integer id){
        tagService.removeById(id);
        return Result.ok("标签删除成功");
    }


}
